<template>
  <div class="edit-online-form">
    <vxe-toolbar>
      <template v-slot:buttons>
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="addEntryVariable">添加变量</el-button>
      </template>
    </vxe-toolbar>
    <el-table key="processVariableList" :data="processVariableList" border size="mini" header-cell-class-name="table-header-gray" :header-cell-style="{background:'#f4f4f4', color:'#717171' }">
      <el-table-column label="序号" header-align="center" align="center" type="index" width="45px" />
      <el-table-column label="变量名称" prop="showName" align="left" min-width="150px" />
      <el-table-column label="变量标识" prop="variableName" align="left" width="150px" />
      <el-table-column label="变量类型" align="center" width="90px">
        <template slot-scope="scope">
          <el-tag size="mini" effect="dark" :type="scope.row.variableType === SysFlowVariableType.TASK ? 'primary' : 'success'">
            {{ SysFlowVariableType.getValue(scope.row.variableType) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="内置变量" align="center" width="90px">
        <template slot-scope="scope">
          <el-tag size="mini" effect="dark" :type="scope.row.builtIn ? 'success' : 'danger'">
            {{ scope.row.builtIn ? '是' : '否' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="98px">
        <template slot-scope="scope">
          <el-button class="table-btn success" size="mini" type="text" :disabled="scope.row.builtin" @click="editEntryVariable(scope.row)">编辑</el-button>
          <el-button class="table-btn delete" size="mini" type="text" :disabled="scope.row.builtin" @click="deleteEntryVariable(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
// import { mapGetters } from 'vuex'
import '@/staticDict/flowStaticDict.js'
/* eslint-disable-next-line */
import rules from '@/utils/validate.js'
/* eslint-disable-next-line */
import { DropdownWidget } from '@/utils/widget.js'
/* eslint-disable-next-line */
import { uploadMixin, statsDateRangeMixin, cachePageMixin } from '@/core/mixins'

/* eslint-disable-next-line */
import { FlowEntryController, FlowEntryVariableController } from '@/api/flowController.js'
import {
  OnlinePageController,
  OnlineColumnController,
  OnlineDatasourceRelationController,
  OnlineVirtualColumnController
} from '@/api/onlineController.js'
import EditFlowEntryVariable from './formEditFlowEntryVariable.vue'

export default {
  name: 'FormEditFlowEntry',
  mixins: [uploadMixin, statsDateRangeMixin, cachePageMixin],
  props: {
    flowEntry: {
      type: Object,
      default: () => {}
    }
  },
  provide() {
    return {
      flowEntry: () => this.formFlowEntryData,
      formList: () => this.defaultFormIdWidget ? this.defaultFormIdWidget.dropdownList : [],
      allVariableList: () => this.processVariableList
    }
  },
  data() {
    return {
      entryDatasource: undefined,
      activeStep: this.SysFlowEntryStep.BASIC,
      formFlowEntryData: {
        entryId: undefined,
        processDefinitionName: undefined,
        processDefinitionKey: undefined,
        categoryId: undefined,
        bindFormType: this.SysFlowEntryBindFormType.ROUTER_FORM,
        pageId: undefined,
        defaultFormId: undefined,
        defaultRouterName: undefined,
        bpmnXml: undefined
      },
      documentClientHeight: this.$store.getters.clientHeight,
      processVariableList: []
    }
  },
  computed: {
    isEdit() {
      return this.flowEntry != null || this.formFlowEntryData.entryId != null
    }
  },
  watch: {
  },
  mounted() {
    // 获取流程页面数据源信息
    this.initFlowDatasourceInfo().then(res => {
      // 获取流程变量
      return this.loadEntryVariableList()
    }).then(res => {
      this.initFlowEntryInfo()
    }).catch(e => {
      console.log(e)
    })
  },
  methods: {
    onClose() {
      this.$emit('close')
    },
    // 初始化流程基础信息
    initFlowEntryInfo() {
      this.formFlowEntryData = {
        processDefinitionName: undefined,
        processDefinitionKey: undefined,
        categoryId: undefined,
        bindFormType: this.SysFlowEntryBindFormType.ONLINE_FORM,
        pageId: undefined,
        defaultFormId: undefined,
        defaultRouterName: undefined,
        bpmnXml: undefined
      }
      this.activeStep = this.SysFlowEntryStep.BASIC

      FlowEntryController.view({
        entryId: this.flowEntry.entryId
      }).then(res => {
        this.formFlowEntryData = {
          ...this.formFlowEntryData,
          ...res.data
        }
        if (this.formFlowEntryData.bindFormType === this.SysFlowEntryBindFormType.ONLINE_FORM) {
          this.defaultFormIdWidget.onVisibleChange(true)
        }
      }).catch(e => {})
    },
    // 获取流程绑定页面数据源信息
    initFlowEntryDatasourceInfo(entryId) {
      return FlowEntryController.viewDatasource({
        entryId
      })
    },
    /**
     * 获取数据模型关联信息
     */
    loadDatasourceRelation() {
      if (this.entryDatasource == null) return Promise.resolve()
      return OnlineDatasourceRelationController.list({
        onlineDatasourceRelationDtoFilter: {
          datasourceId: this.entryDatasource.datasourceId
        }
      })
    },
    // 获取在线表单数据表字段列表
    loadOnlineTableColumns(tableId, owner) {
      if (tableId == null || tableId === '') return Promise.reject()

      return new Promise((resolve, reject) => {
        const params = {
          onlineColumnDtoFilter: {
            tableId
          }
        }

        OnlineColumnController.list(params).then(res => {
          owner.columnList = res.data.dataList
          resolve()
        }).catch(e => {
          reject(e)
        })
      })
    },
    /**
     * 获取数据源下所有表字段
     */
    loadDatasourceAllColumnList() {
      if (this.entryDatasource == null) return Promise.resolve()
      const allHttpCalls = [
        this.loadOnlineTableColumns(this.entryDatasource.masterTableId, this.entryDatasource)
      ]
      this.entryDatasource.relationList.forEach(relation => {
        if (relation.relationType === this.SysOnlineRelationType.ONE_TO_ONE) {
          allHttpCalls.push(this.loadOnlineTableColumns(relation.slaveTableId, relation))
        }
      })

      return Promise.all(allHttpCalls)
    },
    // 获取流程绑定页面数据源信息
    initFlowDatasourceInfo() {
      return new Promise((resolve, reject) => {
        if (this.entryDatasource != null) return resolve()
        if (this.formFlowEntryData.bindFormType === this.SysFlowEntryBindFormType.ONLINE_FORM) {
          OnlinePageController.listOnlinePageDatasource({
            pageId: this.formFlowEntryData.pageId
          }).then(res => {
            this.entryDatasource = res.data.dataList[0]
            return this.loadDatasourceRelation()
          }).then(res => {
            this.entryDatasource.relationList = res.data.dataList || []
            return this.loadDatasourceAllColumnList()
          }).then(res => {
            return OnlineVirtualColumnController.list({
              onlineVirtualColumnDtoFilter: {
                datasourceId: this.entryDatasource.datasourceId
              }
            })
          }).then(res => {
            const virtualColumnList = res.data.dataList
            if (Array.isArray(virtualColumnList)) {
              if (!Array.isArray(this.entryDatasource.columnList)) this.entryDatasource.columnList = []
              this.entryDatasource.columnList.push(...virtualColumnList.map(item => {
                return {
                  ...item,
                  columnId: item.virtualColumnId,
                  columnName: item.objectFieldName,
                  columnComment: item.columnPrompt
                }
              }))
            }
            resolve()
          }).catch(e => {
            reject(e)
          })
        } else {
          this.entryDatasource = null
          resolve()
        }
      })
    },
    // 获取流程变量列表
    loadEntryVariableList() {
      return new Promise((resolve, reject) => {
        const params = {
          flowEntryVariableDtoFilter: {
            entryId: this.formFlowEntryData.entryId || this.flowEntry.entryId
          }
        }

        FlowEntryVariableController.list(params).then(res => {
          this.processVariableList = res.data.dataList
          resolve()
        }).catch(e => {
          reject(e)
        })
      })
    },
    addEntryVariable() {
      this.$dialog.show('添加变量', EditFlowEntryVariable, {
        area: '350px'
      }, {
        entryId: this.formFlowEntryData.entryId || this.flowEntry.entryId,
        datasource: this.entryDatasource
      }).then(res => {
        this.loadEntryVariableList()
      }).catch(e => {})
    },
    editEntryVariable(row) {
      this.$dialog.show('编辑变量', EditFlowEntryVariable, {
        area: '350px'
      }, {
        entryId: this.formFlowEntryData.entryId || this.flowEntry.entryId,
        datasource: this.entryDatasource,
        rowData: row
      }).then(res => {
        this.loadEntryVariableList()
      }).catch(e => {})
    },
    deleteEntryVariable(row) {
      this.$confirm('是否删除此流程变量？').then(res => {
        const params = {
          variableId: row.variableId
        }

        return FlowEntryVariableController.delete(params)
      }).then(res => {
        this.$message.success('删除成功！')
        this.loadEntryVariableList()
      }).catch(e => {})
    }
  }
}
</script>

<style  lang="scss">
  .edit-online-form {
    display: flex;
    flex-direction: column;
    margin: 10px 10px 20px 10px;
    .blueLink {
      color: #409eff;
      font-size: 14px;
      margin-left: 20px;
      cursor: pointer;
    }
    .btnList {
      margin-top:20px;
      display: flex;
      justify-content: right;
      float: right;
      .submitBtn {
        margin-right: 30px;
      }
    }
    .fromFlex {
      height: 36px;
      display: flex;
      align-items: center;
    }
    .base-info {
      display: flex;
      margin-bottom: 20px;
      .basics-info {
        width: 100%;
      }
    }
  }
</style>
